package com.cndw.kungfu.model.battle;

import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.locks.ReentrantLock;

import com.cndw.kungfu.config.Constants;
import com.cndw.kungfu.config.ConstantsRadio;
import com.cndw.kungfu.domain.Player;
import com.cndw.kungfu.ext.TimeProcesser;
import com.cndw.kungfu.model.Context;
import com.cndw.kungfu.model.undercity.PlayerUndercity;
import com.cndw.kungfu.vo.EventNotice;
import com.cndw.rpg.framework.ResponseMessage;

/**
 * 战斗队伍对象
 * 
 * @author fantadust
 * @date 2011-4-27 上午10:58:25
 */
public class Team {

	/**
	 * 队长
	 */
	private Fighter master;

	/**
	 * 队员
	 */
	private Map<Long, Fighter> members = new ConcurrentHashMap<Long, Fighter>(3,0.75f,3);

	private int assignType = 0;

	private int id;
	private int battleId;

	private static final AtomicInteger signNum = new AtomicInteger();
	/**
	 * 成员最大个数
	 */
	public static final int maxMemberSize = 3;

	private Map<Long,Integer> applyIds;

	private ReentrantLock mainLock;
	
	private int signUnderId =0;
	
	
	private int type;

	public Team() {

	}

	public Team(Player player) {
		mainLock = new ReentrantLock();
		id = signNum.incrementAndGet();
		if (id >= Constants.commIntSignMax) {
			signNum.compareAndSet(id, 0);
			id = signNum.incrementAndGet();
		}
		Context.getDataServer().putTeam(this);
		player.setTeamId(id);
		addMember(player.getLikedFighter());
		setMaster(player.getLikedFighter());

	}

	public int getId() {
		return id;
	}

	public void setId(int id) {
		this.id = id;
	}

	public synchronized void addMember(Fighter fighter) {
		members.put(fighter.getUniqueId(), fighter);
	}

	public void memberAdd(Player player) {
		player.setTeamId(id);
		addMember(player.getLikedFighter());
	}

	public void memberRemove(Player player) {
		player.setTeamId(0);
		members.remove(player.getPlayerId());
		boolean changeMaster = false;
		if (master.getUniqueId() == player.getPlayerId()) {
			changeMaster = true;
			if (members.size() >= 1) {
				for (Fighter e : members.values()) {
					master = e;
					upPCManster();
					break;
				}
			} else {// 队伍回收

				Context.getDataServer().teamRemove(id);
			}
		}

		if (members.size() >= 1) {
			EventNotice notice = new EventNotice(ConstantsRadio.team, ConstantsRadio.teamExit);
			notice.comitData(player.getPlayerId());
			if (changeMaster) {
				notice.put("masterId", master.getUniqueId());
			}
			notice.broadcast(getMemberIds());
		}

	}
	
	public void upPCManster(){
		try {
			PlayerUndercity undercity = getUndercity();
			if (undercity != null) {
				undercity.setMasterId(master.getUniqueId());
			}
		} catch (Exception e2) {
			
		}
	}

	public Fighter getFighter(long uniqueId) {
		return members.get(uniqueId);
	}

	public boolean containsUniqueId(long uniqueId) {
		return members.containsKey(uniqueId);
	}

	public Collection<Fighter> getMembers() {
		return members.values();
	}

	public Collection<Fighter> getBattleMembers() {
		if (master.getSceneId() == 0 || members.size() == 1) {
			return getMembers();
		}
		List<Fighter> fighters = new ArrayList<Fighter>();
		for (Fighter e : members.values()) {
			if (e.getSceneId() == master.getSceneId()) {
				fighters.add(e);
			}
		}
		return fighters;
	}

	public Collection<Player> getBattlePlayers() {
		if (master instanceof FighterPlayer == false) {
			return null;
		}
		List<Player> fighters = new ArrayList<Player>();
		for (Fighter e : members.values()) {
			if (e.getSceneId() == master.getSceneId()) {
				fighters.add((Player) e.getSourceObject());
			}
		}
		return fighters;
	}

	public Collection<Player> getAllPlayers() {
		if (master instanceof FighterPlayer == false) {
			return null;
		}
		List<Player> fighters = new ArrayList<Player>();
		for (Fighter e : members.values()) {
			fighters.add((Player) e.getSourceObject());

		}
		return fighters;
	}

	public Set<Long> getMemberIds() {
		return members.keySet();
	}

	public Fighter getMaster() {
		return master;
	}

	public void setMaster(Fighter master) {
		this.master = master;
	}

	public void test() {

	}

	public int getAssignType() {
		return assignType;
	}

	public void applyAdd(long playerId) {
		if (applyIds == null) {
			synchronized (this) {
				if (applyIds == null) {
					applyIds = new HashMap<Long,Integer>();
				}
			}
		}
		applyIds.put(playerId,TimeProcesser.getUnixTime());
	}

	public void applyRemove(long playerId) {
		if (applyIds != null) {
			applyIds.remove(playerId);
		}
	}

	public boolean applyContains(long playerId) {
		if (applyIds != null) {
			return applyIds.containsKey(playerId) && applyIds.get(playerId)+40 >= TimeProcesser.getUnixTime();
		}
		return false;
	}

	/**
	 * 场景广播
	 * 
	 * @param player
	 * @param data
	 * @param actionName
	 */
	public void broadcast(ResponseMessage message) {
		if (master instanceof FighterPlayer) {
			for (long playerId : members.keySet()) {// 暂不做同步
				Context.getTcpServer().broadcastResMsg(message, playerId);
			}

		}
	}

	public void broadcast(Object obj, String actionName) {
		Context.getTcpServer().broadcast(obj, actionName, getMemberIds());
	}

	public void broadcast(Object obj, String actionName, int sceneId) {
		for (Fighter fighter : members.values()) {// 暂不做同步
			if (fighter.getSceneId() == sceneId) {
				Context.getTcpServer().broadcast(obj, actionName, fighter.getUniqueId());
			}
		}
	}

	public boolean isMaster(long playerId) {
		if (master == null) {
			return false;
		}
		return master.getUniqueId() == playerId;
	}

	/**
	 * 执行队长命令
	 * 
	 * @param mode
	 * @param action
	 * @param parameter
	 */
	public void broadcastMaster(String mode, String action, Object... parameter) {
		if (members.size() == 1) {
			return;
		}
		EventNotice eventNotice = new EventNotice(ConstantsRadio.team, ConstantsRadio.teamCommand);
		eventNotice.put("cm", mode);
		eventNotice.put("ca", action);
		eventNotice.put("cp", parameter);
		for (Fighter fighter : members.values()) {// 暂不做同步
			if (fighter.getUniqueId() != master.getUniqueId() && fighter.getSceneId() == master.getSceneId()) {
				if (((Player) fighter.getSourceObject()).stateContains(Constants.playerState64_market)) {
					continue;
				}
				eventNotice.broadcast(fighter.getUniqueId());
			}
		}
	}

	public PlayerUndercity getUndercity() {
		return Context.getUndercityServer().getPlayerUndercity(master.getUniqueId());
	}

	public int getBattleId() {
		return battleId;
	}

	public void setBattleId(int id) {
		battleId = id;
	}

	public ReentrantLock getMainLock() {
		return mainLock;
	}

	public int getSignUnderId() {
		return signUnderId;
	}

	public void setSignUnderId(int signUnderId) {
		this.signUnderId = signUnderId;
	}

	public int getType() {
		return type;
	}

	public void setType(int type) {
		this.type = type;
	}
	

}
